﻿

module Sustainalytics.Tools.Admin {


    import Common = Sustainalytics.Common;
    import AdminAccounts = Sustainalytics.Accounts.Admin;
    import CommonAdmin = Sustainalytics.Common.Admin;
    import ScreeningTool = Sustainalytics.Screening;
  
    export class ReportFTPController {

        public $scope: ng.IScope;

        private notificationFactory: Common.INotificationFactory;
        private $q: ng.IQService;

        public isUnselected: string = null;
        public isLoading: boolean;
        public accountsList: AdminAccounts.AccountsDto[] = null;
        public selectedAccount: AdminAccounts.AccountsDto = null;
        public accountId: string;
        public isEditFtpReport: string = null;
        public isEditFtpSettings: string = null;
        public isNewFTPReport: boolean;
        public isNewFTPSettings: boolean = false;

        public persistedFtpReports: Array<FtpClientReportDto> = null;
        public ftpReportsUI: Array<FtpClientReportDto> = null;
        public ftpSettingsUI: ReportFTPDto = null;
        public persistedFtpSettings: Array<ReportFTPDto> = null;
        public editedClientReport: FtpClientReportDto = null; 

        public ftpServerAddress: string = null;
        public ftpServerPort: number = null;        
        public ftpServerType: string = null;

        public ftpServerUser: string = null;
        public ftpServerPassword: string = null;

        public ftpDirectoryPath: string = null;

        public ftpReportType: string = null;
        public ftpFrequencyType: string = null;

        public ftpReportTypes: ReportFTPUtil[] = null;
        public ftpServerTypes: FTPServerUtil[] = null;
        public ftpReportFrequencies: ReportFrequencyUtil[] = null;

        public accountFiltersUI: Array<ScreeningTool.FilterDto> = null;
        public persistedAccountFiltersUI: Array<ScreeningTool.FilterDto> = null;
        
        constructor(
            $scope: ng.IScope,
            $rootScope,
            $q: ng.IQService,
            $location: ng.ILocationService,
            $http: ng.IHttpService,
            private AccountsService: AdminAccounts.AccountsService,
            private ReportFTPService: IReportFTPService,
            private FtpClientReportService: IFtpClientReportService,
            private FilterService: Screening.IFilterService,
            notificationFactory: Common.INotificationFactory) {

            var ctx = this;
            $scope['reportFTP'] = this;

            ctx.$q = $q;
            ctx.$scope = $scope;
            ctx.notificationFactory = notificationFactory;

            ctx.isUnselected = "----Select----";
            ctx.getAccountSelectOptions();

            ctx.listFTPServerTypes();

            ctx.listFTPReportTypes();
            ctx.listFTPReportFrequencies();

        }

        private listFTPReportTypes() {
            var ctx = this;

            ctx.ftpReportTypes = new Array<ReportFTPUtil>();

            ctx.ftpReportTypes[0] = new ReportFTPUtil();
            ctx.ftpReportTypes[0].key = ReportTypeEnum.Report;
            ctx.ftpReportTypes[0].value = "Report";

            ctx.ftpReportTypes[1] = new ReportFTPUtil();
            ctx.ftpReportTypes[1].key = ReportTypeEnum.Filter;
            ctx.ftpReportTypes[1].value = "Filter";          
        }

        private listFTPServerTypes() {
            var ctx = this;

            ctx.ftpServerTypes = new Array<FTPServerUtil>();

            ctx.ftpServerTypes[0] = new FTPServerUtil();
            ctx.ftpServerTypes[0].key = FtpServerTypeEnum.Ftp;
            ctx.ftpServerTypes[0].value = "FTP";

            ctx.ftpServerTypes[1] = new FTPServerUtil();
            ctx.ftpServerTypes[1].key = FtpServerTypeEnum.FtpSSL;
            ctx.ftpServerTypes[1].value = "FTP/SSL";

            ctx.ftpServerTypes[2] = new FTPServerUtil();
            ctx.ftpServerTypes[2].key = FtpServerTypeEnum.FtpSSH;
            ctx.ftpServerTypes[2].value = "SSH-FTP";
          
        }

        private listFTPReportFrequencies() {
            var ctx = this;

            ctx.ftpReportFrequencies = new Array<ReportFrequencyUtil>();
           
            ctx.ftpReportFrequencies[0] = new ReportFrequencyUtil();
            ctx.ftpReportFrequencies[0].key = FrequencyEnum.Daily;
            ctx.ftpReportFrequencies[0].value = "Daily";

            ctx.ftpReportFrequencies[1] = new ReportFrequencyUtil();
            ctx.ftpReportFrequencies[1].key = FrequencyEnum.Weekly;
            ctx.ftpReportFrequencies[1].value = "Weekly";

            ctx.ftpReportFrequencies[2] = new ReportFrequencyUtil();
            ctx.ftpReportFrequencies[2].key = FrequencyEnum.SemiMonthly;
            ctx.ftpReportFrequencies[2].value = "SemiMonthly";

            ctx.ftpReportFrequencies[3] = new ReportFrequencyUtil();
            ctx.ftpReportFrequencies[3].key = FrequencyEnum.Monthly;
            ctx.ftpReportFrequencies[3].value = "Monthly";

            ctx.ftpReportFrequencies[4] = new ReportFrequencyUtil();
            ctx.ftpReportFrequencies[4].key = FrequencyEnum.Quarterly;
            ctx.ftpReportFrequencies[4].value = "Quarterly";               
        }

        private getAccountSelectOptions() {
            var ctx = this;

            var listOptions = new CommonAdmin.HttpGetOptionsDto();

            listOptions.skip = 0;
            listOptions.take = 5000;
            listOptions.orderBy = ['name'];
            listOptions.orderAscending = true;
          
            var promise = ctx.AccountsService.accountsGetList(listOptions, '', '', null);

            promise.then(data => {
                ctx.accountsList = data;
            });

            return promise;
        }

        public accountIsSelected(): boolean {
            var ctx = this;
            if (ctx.selectedAccount != null && (ctx.accountId != null || ctx.accountId !== ""))
                return true;

            return false;
        }

        public loadFTPReportsWithServerSettings() {
            var ctx = this;
            var selectedAccounts = ctx.accountsList.filter(function (el) {
                return el.id === ctx.accountId;
            });

            if (selectedAccounts.length === 1) {
                ctx.selectedAccount = selectedAccounts[0];
            }

            ctx.getClientFTPReportsByAccountId(ctx.accountId);
            ctx.getFTPServerSettingsByAccountId(ctx.accountId);
            ctx.getExistingReportsAndFiltersByAccountId(ctx.accountId);         
        }

        private getClientFTPReportsByAccountId(accountId: string): ng.IPromise<FtpClientReportDto[]> {
            var ctx = this;
            var promise = ctx.FtpClientReportService.loadFtpClientReportsForAccount(accountId);

            promise.then((ftpClientReports: FtpClientReportDto[]) => {

                if (ftpClientReports == null || ftpClientReports == undefined || ftpClientReports.length == 0)
                    ctx.ftpReportsUI = new Array<FtpClientReportDto>();
                else {
                    ctx.ftpReportsUI = ftpClientReports;
                }               
                            
                //Copy the elements persisted in MONGO to the destination array, that will be unaffected by Edit operations
                ctx.persistedFtpReports = new Array<FtpClientReportDto>();

                if (ctx.ftpReportsUI != null && ctx.ftpReportsUI != undefined && ctx.ftpReportsUI.length > 0) {
                    for (var i = 0; i < ctx.ftpReportsUI.length; i++) {
                        ctx.persistedFtpReports.push(ctx.ftpReportsUI[i]);
                    }
                }                

            },
                (errorReason => { console.log(errorReason); })
                ).finally(() => { ctx.isLoading = false; });

            return promise;
        }

        private getExistingReportsAndFiltersByAccountId(accountId: string): ng.IPromise<ScreeningTool.FilterDto[]> {
            var ctx = this;
            var promise = ctx.FilterService.getAccountFilters(accountId);

            promise.then((accountReportsAndFilters: ScreeningTool.FilterDto[]) => {

                if (accountReportsAndFilters == null || accountReportsAndFilters == undefined || accountReportsAndFilters.length == 0)
                    ctx.accountFiltersUI = new Array<ScreeningTool.FilterDto>();
                else {
                    ctx.accountFiltersUI = accountReportsAndFilters;
                }               
                            
                //Copy the elements persisted in MONGO to the destination array, that will be unaffected by Edit operations
                //ctx.persistedAccountFiltersUI = new Array<ScreeningTool.FilterDto>();

                //if (ctx.accountFiltersUI != null && ctx.accountFiltersUI != undefined && ctx.accountFiltersUI.length > 0) {
                //    for (var i = 0; i < ctx.accountFiltersUI.length; i++) {
                //        ctx.persistedAccountFiltersUI.push(ctx.accountFiltersUI[i]);
                //    }
                //}

            },
                (errorReason => { console.log(errorReason); })
                ).finally(() => { ctx.isLoading = false; });

            return promise;
        }

        public findFTPServerTypeEnumKey(idM: any): FtpServerTypeEnum {
            var ctx = this;
            if (ctx.ftpServerTypes != null && ctx.ftpServerTypes != undefined) {
                for (var i = 0; i < ctx.ftpServerTypes.length; i++) {
                    if (ctx.ftpServerTypes[i].value === idM)
                        return ctx.ftpServerTypes[i].key;
                }
            }

            return 0;
        }

        public findFTPServerTypeEnumName(idM: any): string {
            var ctx = this;
            if (ctx.ftpServerTypes != null && ctx.ftpServerTypes != undefined) {
                for (var i = 0; i < ctx.ftpServerTypes.length; i++) {
                    if (ctx.ftpServerTypes[i].key === idM)
                        return ctx.ftpServerTypes[i].value;
                }
            }

            return "";
        }

        public findReportTypeEnumKey(idM: any): ReportTypeEnum {
            var ctx = this;
            if (ctx.ftpReportTypes != null && ctx.ftpReportTypes != undefined) {
                for (var i = 0; i < ctx.ftpReportTypes.length; i++) {
                    if (ctx.ftpReportTypes[i].value === idM)
                        return ctx.ftpReportTypes[i].key;
                }
            }

            return 0;
        }

        public findReportTypeEnumName(idM: any): string {
            var ctx = this;
            if (ctx.ftpReportTypes != null && ctx.ftpReportTypes != undefined) {
                for (var i = 0; i < ctx.ftpReportTypes.length; i++) {
                    if (ctx.ftpReportTypes[i].key === idM)
                        return ctx.ftpReportTypes[i].value;
                }
            }

            return "";
        }


        public findFrequencyTypeEnumKey(idM: any): FrequencyEnum {
            var ctx = this;
            if (ctx.ftpReportFrequencies != null && ctx.ftpReportFrequencies != undefined) {
                for (var i = 0; i < ctx.ftpReportFrequencies.length; i++) {
                    if (ctx.ftpReportFrequencies[i].value === idM)
                        return ctx.ftpReportFrequencies[i].key;
                }
            }

            return 0;
        }

        public findFrequencyTypeEnumName(idM: any): string {
            var ctx = this;
            if (ctx.ftpReportFrequencies != null && ctx.ftpReportFrequencies != undefined) {
                for (var i = 0; i < ctx.ftpReportFrequencies.length; i++) {
                    if (ctx.ftpReportFrequencies[i].key === idM)
                        return ctx.ftpReportFrequencies[i].value;
                }
            }

            return "";
        }

        public findReportOrFilterName(idM: any): string {
            var ctx = this;
            if (ctx.accountFiltersUI != null && ctx.accountFiltersUI != undefined) {
                for (var i = 0; i < ctx.accountFiltersUI.length; i++) {
                    if (ctx.accountFiltersUI[i].id === idM)
                        return ctx.accountFiltersUI[i].name;
                }
            }

            return "";
        }

        public findReportOrFilterId(idM: any): string {
            var ctx = this;
            if (ctx.accountFiltersUI != null && ctx.accountFiltersUI != undefined) {
                for (var i = 0; i < ctx.accountFiltersUI.length; i++) {
                    if (ctx.accountFiltersUI[i].name === idM)
                        return ctx.accountFiltersUI[i].id;
                }
            }

            return "";
        }

        private getFTPServerSettingsByAccountId(accountId: string): ng.IPromise<ReportFTPDto> {

            var ctx = this;
            var promise = ctx.ReportFTPService.loadReportFtpForAccountId(accountId);

            promise.then((ftpSettings: ReportFTPDto) => {

                if (ftpSettings != null && ftpSettings != undefined ) {

                    ctx.ftpSettingsUI = ftpSettings;

                    ctx.ftpServerAddress = ctx.ftpSettingsUI.serverAddress;
                    ctx.ftpServerPort = ctx.ftpSettingsUI.serverPort;

                    var serverTypeName: string = ctx.findFTPServerTypeEnumName(ctx.ftpSettingsUI.ftpServerType);
                    ctx.ftpServerType = serverTypeName;

                    ctx.ftpServerUser = ctx.ftpSettingsUI.username;
                    ctx.ftpServerPassword = ctx.ftpSettingsUI.password;

                    ctx.ftpDirectoryPath = ctx.ftpSettingsUI.directoryPath;

                    ctx.isEditFtpSettings = undefined;
                    ctx.isNewFTPSettings = false;
                    

                    if (ctx.ftpServerAddress == undefined && ctx.ftpServerPort == undefined && ctx.ftpServerUser == undefined && ctx.ftpServerPassword == undefined && ctx.ftpDirectoryPath == undefined)
                    {
                        ctx.isNewFTPSettings = true;
                    }
                }                               
                            
                //Copy the elements persisted in MONGO to the destination array, that will be unaffected by Edit operations            
                if (ctx.ftpSettingsUI != null && ctx.ftpSettingsUI != undefined) {

                    ctx.persistedFtpSettings = new Array<ReportFTPDto>();
                    ctx.persistedFtpSettings.push(ctx.ftpSettingsUI);

                }
            },
                (errorReason => { console.log(errorReason); })
                ).finally(() => { ctx.isLoading = false; });

            return promise;
        }

        public toggleEditModeFtpReport(id: string) {
            var ctx = this;

            if (id !== undefined)
                ctx.isEditFtpReport = id;

            else {
                ctx.isEditFtpReport = undefined;
            }
        }

        public cancelEditAddClientFTPReport(id: string) {
            var ctx = this;

            if (id !== undefined)
                ctx.isEditFtpReport = undefined;
            
            //Repopulate Client FTP reports list
            ctx.notificationFactory.success('Operation was cancelled.');
            ctx.getClientFTPReportsByAccountId(ctx.accountId);
        }

        public getToggleStateFtpReport(id: string): boolean {
            var ctx = this;

            if (id === ctx.isEditFtpReport)
                return true;

            return false;
        }


        public toggleEditModeFtpSettings(id: string) {
            var ctx = this;

            if (id !== undefined)
                ctx.isEditFtpSettings = id;

            else {
                ctx.isEditFtpSettings = undefined;
               // ctx.isNewFTPSettings = true;
            }
        }

        public getToggleStateFtpSettings(id: string): boolean {
            var ctx = this;

            if (id === ctx.isEditFtpSettings)
                return true;

            return false;
        }

        public isFTPSettingsTableRowForDisplay(): boolean {
            var ctx = this;          

            if ((ctx.accountId != null && ctx.accountId != '' && ctx.accountId != undefined)
                &&  ((!ctx.isNewFTPSettings && ctx.isNewFTPSettings != null)
                ||  (ctx.isNewFTPSettings && ctx.isEditFtpSettings != null && ctx.isEditFtpSettings != undefined)))
                return true;                
                
            return false;
        }

        public isAccountSelected(): boolean {
            var ctx = this;

            if ((ctx.accountId != null && ctx.accountId != '' && ctx.accountId != undefined))
                return true;

            return false;
        }

        public isEditMode(): boolean {
            var ctx = this;

            if (ctx.isEditFtpSettings != null && ctx.isEditFtpSettings != undefined)
                return true;

            return false;
        }

        public isAccountSelectedWithEditMode(): boolean {
            var ctx = this;

            if ((ctx.accountId != null && ctx.accountId != '' && ctx.accountId != undefined)
                && (ctx.isEditFtpSettings != null && ctx.isEditFtpSettings != undefined))
                return true;

            return false;
        }

        public isSaveButtonForDisplay(): boolean {
            var ctx = this;

            if ((ctx.accountId != null && ctx.accountId != '' && ctx.accountId != undefined)
                && (ctx.isEditFtpSettings != null && ctx.isEditFtpSettings != undefined))
                return true;

            return false;
        }

        public isEditButtonForDisplay(): boolean {
            var ctx = this;

            if ((ctx.accountId != null && ctx.accountId != '' && ctx.accountId != undefined)
                && (ctx.isEditFtpSettings == null || ctx.isEditFtpSettings == undefined))                
                return true;

            return false;
        }

        public saveFtpSettings(item: any) {
            var ctx = this;
            var def = this.$q.defer();

            var message = ctx.validateFTPSettings();
            if (message === "") {

                //if (ctx.ensureNameNotDuplicate(item)){
                //    ctx.notificationFactory.error('', 'Save fails. Please ensure that the Profile Name is unique on Platform');
                //    def.reject();
                //}
                //else {              
                                                  
                                                
                //Handle Edit FTP Server Settings Section 

                if (!ctx.isNewFTPSettings) {

                    var promise = ctx.ReportFTPService
                        .updateReportFtp(ctx.ftpSettingsUI)
                        .success(data => {
                        ctx.notificationFactory.success('Save FTP Server settings succeeded');
                      //  ctx.getClientFTPReportsByAccountId(ctx.accountId);

                        ctx.toggleEditModeFtpSettings(undefined);

                        def.resolve(data);
                    })
                        .error(err => {
                            ctx.notificationFactory.error('', 'The save operation failed. Possible reasons: invalid FTP address, FTP server timeout or access denied. Please ensure that the FTP server settings are valid for the target machine');
                        def.reject();

                    });

                    promise.then((data) => {

                    },
                        (errorReason => { console.log(errorReason); })
                        ).finally(() => { ctx.isLoading = false; });
                }
                else {

                    //Handle Add new FTP Server Settings Section  - for the case where no settings are persisted

                    ctx.ftpSettingsUI.accountId = ctx.accountId;


                    var promise = ctx.ReportFTPService
                        .createReportFtp(ctx.ftpSettingsUI)
                        .success(data => {
                       // ctx.getClientFTPReportsByAccountId(ctx.accountId);
                        ctx.isNewFTPSettings = false;

                        ctx.toggleEditModeFtpSettings(undefined);
                        ctx.notificationFactory.success('Add new FTP Server settings succeeded');
                        def.resolve(data);
                    })
                        .error(err => {
                            ctx.notificationFactory.error('', 'The save operation failed. Possible reasons: invalid FTP address, FTP server timeout or access denied. Please ensure that the FTP server settings are valid for the target machine');
                        def.reject();

                    });

                    promise.then((data) => {
                    },
                        (errorReason => { console.log(errorReason); })
                        ).finally(() => { ctx.isLoading = false; });
                }

                // }                
            }
            else {
                ctx.notificationFactory.error('', message);
            }

            return def.promise;
        }

        private validateFTPSettings() {
            var ctx = this;
            var message = "";

            if (ctx.isNewFTPSettings)
            {
                ctx.ftpSettingsUI = new ReportFTPDto();
            }
            
            ctx.ftpSettingsUI.accountId = ctx.accountId;

            var ftpServerTypeNr: FtpServerTypeEnum = ctx.findFTPServerTypeEnumKey(ctx.ftpServerType);           

            ctx.ftpSettingsUI.ftpServerType = ftpServerTypeNr;           
            ctx.ftpSettingsUI.serverAddress = ctx.ftpServerAddress;   
            ctx.ftpSettingsUI.serverPort  = ctx.ftpServerPort;
            ctx.ftpSettingsUI.username    = ctx.ftpServerUser;
            ctx.ftpSettingsUI.password    = ctx.ftpServerPassword;                    
            ctx.ftpSettingsUI.directoryPath = ctx.ftpDirectoryPath;           

            if (ctx.ftpSettingsUI.ftpServerType == undefined || ctx.ftpSettingsUI.accountId == undefined || ctx.ftpSettingsUI.serverAddress == undefined || ctx.ftpSettingsUI.serverPort == undefined) {
                console.log("Some fields got undefined.");
                console.log("FTP Server Type: " + ctx.ftpSettingsUI.ftpServerType + ", Account Id: " + ctx.ftpSettingsUI.accountId + "; Server Address:" + ctx.ftpSettingsUI.serverAddress
                    + ", Server Port: " + ctx.ftpSettingsUI.serverPort + ", User Name: " + ctx.ftpSettingsUI.username + ", Password: " + ctx.ftpSettingsUI.password);

                message += "Please check the following field(s): ";

                if (ctx.ftpSettingsUI.ftpServerType == undefined)
                    message += "<br/> FTP Server Type";
                if (ctx.ftpSettingsUI.accountId == undefined)
                    message += "<br/> Account";
                if (ctx.ftpSettingsUI.serverAddress == undefined)
                    message += "<br/> Server Address must be a valid FTP address.";
                if (ctx.ftpSettingsUI.serverPort == undefined)
                    message += "<br/> Server Port";
                if (ctx.ftpSettingsUI.username == undefined)
                    message += "<br/> User Name";
                if (ctx.ftpSettingsUI.password == undefined)
                    message += "<br/> Password";

            }           

            return message;
        }

        public saveClientFTPReport(item: any) {
            var ctx = this;
            var def = this.$q.defer();

            (<FtpClientReportDto>item).accountId = ctx.accountId;         
            

            var message = ctx.validateFTPReport(item);
            if (message === "") {

                //if (ctx.ensureNameNotDuplicate(item)){
                //    ctx.notificationFactory.error('', 'Save fails. Please ensure that the Profile Name is unique on Platform');
                //    def.reject();
                //}
                //else {                                        
                                                            
                //Handle Edit FTP Report Section 

                if (!ctx.isNewFTPReport) {                    
                  
                    var promise = ctx.FtpClientReportService
                        .modifyFtpClientReport(<FtpClientReportDto>item)
                        .success(data => {
                        ctx.notificationFactory.success('Save FTP Report succeeded');
                        ctx.getClientFTPReportsByAccountId(ctx.accountId);

                        ctx.toggleEditModeFtpReport(undefined);                        

                        def.resolve(data);
                    })
                        .error(err => {
                            ctx.notificationFactory.error('', 'Save FTP Report fails. Please ensure that all the fields are selected');
                        def.reject();

                    });

                    promise.then((data) => {

                    },
                        (errorReason => { console.log(errorReason); })
                        ).finally(() => { ctx.isLoading = false; });
                }
                else {

                    //Handle Add new FTP Report Section 

                    (<FtpClientReportDto>item).accountId = ctx.accountId;

                    var promise = ctx.FtpClientReportService
                        .addFtpClientReport(<FtpClientReportDto>item)
                        .success(data => {
                        ctx.getClientFTPReportsByAccountId(ctx.accountId);
                        ctx.isNewFTPReport = false;

                        ctx.toggleEditModeFtpReport(undefined);
                        ctx.notificationFactory.success('Add FTP Report succeeded');
                        def.resolve(data);
                    })
                        .error(err => {
                            ctx.notificationFactory.error('', 'Save FTP Report fails. Please ensure that all the fields are selected');
                        def.reject();

                    });

                    promise.then((data) => {
                    },
                        (errorReason => { console.log(errorReason); })
                        ).finally(() => { ctx.isLoading = false; });
                }

                // }                
            }
            else {
                ctx.notificationFactory.error('', message);
            }

            return def.promise;
        }

        private validateFTPReport(item: any) {
            var ctx = this;
            var message = "";                       
          
            //if (item.name == null   || item.name == undefined   || item.accountId == undefined || item.reportId == undefined   || item.frequency == undefined) {
             if ( item.accountId == undefined || item.reportId == undefined || item.frequency == undefined) {
                console.log("Some fields got undefined.");
               
               // console.log("FTP Report Name: " + item.name + ", Account Id: " + item.accountId + "; Report Type:" + item.reportId + ", Recurrence: " + item.frequency);
                console.log("FTP Report  Account Id: " + item.accountId + "; Report Type:" + item.reportId + ", Recurrence: " + item.frequency);

                message += "Please check the following field(s): ";

                //if (item.name == undefined)
                //    message += "<br/> FTP Report name";

                if (item.accountId == undefined)
                    message += "<br/> Account";
               
                if (item.reportId == undefined)
                    message += "<br/> Report or Filter";

                if (item.frequency == undefined)
                    message += "<br/> Recurrence";
            }
            //else {
            //    var newText = item.name;

            //    if (newText.length > 49) {
            //        message += "The FTP Report name should have maximum 49 characters.";
            //    }
            //}

            return message;
        }


        public addClientFTPReport() {
            var ctx = this;
                        
                ctx.editedClientReport = new FtpClientReportDto();

                ctx.editedClientReport.id = "00000000-0000-0000-1111-000000000000";
               
                //Suggested Name
                //ctx.editedClientReport.name = "New Report_1";
                           
                ctx.isNewFTPReport = true;

                ctx.ftpReportsUI.unshift(ctx.editedClientReport);
                ctx.toggleEditModeFtpReport("00000000-0000-0000-1111-000000000000");

            
            //else {
            //    ctx.notificationFactory.error('', "ESG Profiles number associated to this account is 20, the maximum allowed. Please delete at least one ESG Profile.");
            //}
        }


        public deleteClientFTPReport(item: any) {
            var ctx = this;
            var def = this.$q.defer();

            var itemId = item.id;
            var accountId = item.accountId;           

            if (confirm("Ar you sure you want to delete this FTP Report?")) {
                var promise = ctx.FtpClientReportService
                    .deleteReportFtpForAccountAndReportId(accountId, itemId)
                    .success(data => {
                    //Ensure removal of Client FTP Report from the Grid Items
                    ctx.removeFtpReportFromUIGrid(itemId);
                    ctx.notificationFactory.success('Delete operation succeeded');
                    def.resolve(data);
                })
                    .error(err => {
                    ctx.notificationFactory.error('', 'Delete operation fails. Please try again.');
                    def.reject();
                });

                promise.then((data) => {

                },
                    (errorReason => { console.log(errorReason); })
                    ).finally(() => { ctx.isLoading = false; });
            }
        }

        private removeFtpReportFromUIGrid(itemId: string) {
            var ctx = this;

            for (var i = 0; i < ctx.ftpReportsUI.length; i++) {
                if (ctx.ftpReportsUI[i].id === itemId) {
                    
                    //Only remove 1 FTP Report --> the one that matches the FTP Report Id; This ensures that the  FTP Report UI Grid is kept in sync
                    ctx.ftpReportsUI.splice(i, 1);
                }
            }
        } 

    }

     

    // register controller with Tools Angular module
    var mod = angular.module(toolsAdminModuleName);

    mod.controller('ReportFTPController',
        ['$scope', '$rootScope', '$q', '$location', '$http', 'AccountsService', 'ReportFTPService', 'FtpClientReportService', 'FilterService', 'notificationFactory', Sustainalytics.Tools.Admin.ReportFTPController]);
} 